package org.xbdframework.context.support;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.xbdframework.context.XbdApplicationEvent;
import org.xbdframework.context.XbdApplicationEventPublisher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public abstract class AbstractXbdApplicationEventPublisherAdapter<E extends XbdApplicationEvent>
		implements XbdApplicationEventPublisher<E>, ApplicationEventPublisherAware {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected ApplicationEventPublisher applicationEventPublisher;

	protected void execute(E e) {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("事件发布器{}监听到来源{}的事件已处理完成，于{}额外的业务逻辑处理开始", new Object[] {
					this.getClass().getSimpleName(), e.getSource(), now() });
		}

		if (this.logger.isDebugEnabled()) {
			this.logger.debug("事件发布器{}监听到来源{}的事件已处理完成，于{}额外的业务逻辑处理完成", new Object[] {
					this.getClass().getSimpleName(), e.getSource(), now() });
		}
	}

	@Override
	public void publishEvent(E e) {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("事件发布器{}监听到来源{}的事件，于{}处理开始，事件详细内容为{}",
					new Object[] { this.getClass().getSimpleName(), e.getSource(), now(),
							e.toString() });
		}

		this.applicationEventPublisher.publishEvent(e);

		execute(e);

		if (this.logger.isDebugEnabled()) {
			this.logger.debug("事件发布器{}监听到来源{}的事件，于{}处理完成，事件详细内容为{}",
					new Object[] { this.getClass().getSimpleName(), e.getSource(), now(),
							e.toString() });
		}
	}

	@Override
	public void setApplicationEventPublisher(
			ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}

	protected String now() {
		return LocalDateTime.now()
				.format(DateTimeFormatter.ofPattern("yyyy/mm/dd HH:mm:ss"));
	}

}
